import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_network/toast.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'color.dart';

///Ceate author: ljr
///title：自定义加减数字变化控件

// ignore: must_be_immutable
class NumChangeWidget extends StatefulWidget {
  int num;
  int minNum ;
  int maxNum;
  String limitTips;
  final ValueChanged<int>? onFinishChanged;
  final ValueChanged<int>? onValueChanged;
  bool canEdit;             //能否手动编辑数量

  NumChangeWidget(
      { this.num = 0, this.onFinishChanged, this.minNum = 0, this.maxNum = -1, this.limitTips = '',this.canEdit = true, this.onValueChanged});

  @override
  _NumChangeWidgetState createState() {
    return _NumChangeWidgetState();
  }
}

class _NumChangeWidgetState extends State<NumChangeWidget> {
  TextEditingController? _textEditingController;
  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _textEditingController = TextEditingController.fromValue(TextEditingValue(
        text: '${widget.num.toString() == null ? "" : widget.num.toString()}',  //判断keyword是否为空
        // 保持光标在最后

        selection: TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream,
            offset: '${widget.num.toString()}'.length))));

  }


  KeyboardActionsConfig _buildConfig(BuildContext context) {
    return KeyboardActionsConfig(
      keyboardActionsPlatform: KeyboardActionsPlatform.ALL,
      keyboardBarColor: Colors.grey[200],
      nextFocus: false,
      actions: [
        KeyboardActionsItem(
          displayArrows: false,
          focusNode: _focusNode,
          toolbarButtons: [
                (node) {
              return InkWell(
                onTap: (){
                  node.unfocus();
                  if (widget.maxNum != -1) {
                    if (widget.num > widget.maxNum) {
                      if(widget.limitTips != null && widget.limitTips != ''){
                        widget.num = widget.maxNum;
                        flutterToast(msg: widget.limitTips);
                        setState(() {});
                      }
                    }
                  }

                  if (widget.num < widget.minNum) {
                    if(widget.limitTips != null && widget.limitTips != ''){
                      widget.num = widget.minNum;
                      flutterToast(msg: widget.limitTips);
                      setState(() {});
                    }
                  }

                  if (widget.onFinishChanged != null) {
                    widget.onFinishChanged!(widget.num);
                  }
                },
                child: Padding(
                  padding: EdgeInsets.only(right: 20.0.w),
                  child: Text(
                    '完成',
                    style: TextStyle(
                      color: ColorManager.color2A2A2A,
                      fontSize: 15.sp,
                      fontWeight: FontWeight.w500
                    ),
                  ),
                ),
              );
            }
          ],
        ),

      ],
    );
  }


  @override
  Widget build(BuildContext context) {
    return KeyboardActions(
      config: _buildConfig(context),
      disableScroll: true,
      child: Container(
        height: 26.w,
        width: 91.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(2.0)),
          border: Border.all(color: ColorManager.colorF2F2F2, width: 0.5),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            GestureDetector(
              onTap: _minusNum,
              child: Container(
                width: 26.w,
                height: 26.w,
                color: Colors.white,
                alignment: Alignment.center,
                child: Icon(
                  Icons.remove,
                  size: 16,
                  color: widget.num == widget.minNum ? ColorManager.colorCCCCCC : Colors.black,
                ), // -
              ),
            ),
            Container(
              width: 0.5,
              color: ColorManager.colorF2F2F2,
            ),
            Container(
              width: 36.w,
              height: 26.w,
              child: TextField(
                focusNode: _focusNode,
                //初始化的时候光标保持在文字最后,设置初始文字
                // controller: TextEditingController(text: widget.subtitle),
                // controller: _textEditingController,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: '${widget.num.toString( ) == null ? "" : widget.num.toString()}',  //判断keyword是否为空
                    // 保持光标在最后
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: '${widget.num.toString()}'.length)),

                )),
                maxLines: 1,//最大行数
                minLines: 1,

                // textInputAction: TextInputAction.done,
                // autocorrect: true,
                keyboardType: TextInputType.number,
                //是否自动更正
                cursorColor: ColorManager.color353535,
                // autofocus: true,
                //是否自动对焦
                // textAlign: TextAlign.right,
                //文本对齐方式
                textAlign: TextAlign.center,
                // textAlignVertical: TextAlignVertical.center,
                style: TextStyle(fontSize: 15.sp, color: ColorManager.color2A2A2A),
                //输入文本的样式
                decoration: InputDecoration(
                  isDense: true,
                    border: InputBorder.none,
                  contentPadding:  EdgeInsets.only(top: 3.w),
                ),
                onChanged: (text) {
                  //内容改变的回调
                  setState(() {
                    widget.num = int.parse(text);

                    if (widget.maxNum != -1) {
                      if (widget.num > widget.maxNum) {
                        if(widget.limitTips != null && widget.limitTips != ''){
                          widget.num = widget.maxNum;
                          flutterToast(msg: widget.limitTips);
                        }
                        // return;
                      }
                    }

                    if (widget.onValueChanged != null) {
                      widget.onValueChanged!(widget.num);
                    }
                    setState(() {});
                  });
                },
                onSubmitted: (text) {
                  //内容提交(按回车)的回调
                  print('submit $text');
                },
                enabled: widget.canEdit, //是否禁用
              ),
              // Text(
              //   widget.num.toString(),
              //   maxLines: 1,
              //   style:
              //       TextStyle(fontSize: 15.sp, color: ColorManager.color_2A2A2A),
              // ),
            ),
            Container(
              width: 0.5,
              color: ColorManager.colorF2F2F2,
            ),
            GestureDetector(
              onTap: _addNum,
              child: Container(
                width: 26.w,
                height: 26.w,
                color: Colors.white,
                alignment: Alignment.center,
                child: Icon(Icons.add,
                    size: 16,
                  color: widget.num == widget.maxNum ? ColorManager.colorCCCCCC : Colors.black,
                ), // +
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _minusNum() {
    if (widget.num == widget.minNum) {
      return;
    }

    setState(() {
      widget.num -= 1;

      if (widget.onFinishChanged != null) {
        widget.onFinishChanged!(widget.num);
      }
    });
  }

  void _addNum() {
    if (widget.maxNum != -1) {
      if (widget.num == widget.maxNum) {
        if(widget.limitTips != null && widget.limitTips != ''){
          flutterToast(msg: widget.limitTips);
        }
        return;
      }
    }
    setState(() {
      widget.num += 1;

      if (widget.onFinishChanged != null) {
        widget.onFinishChanged!(widget.num);
      }
    });
  }
}
